package com.topone.controller;

import com.topone.Enum.ResultEnum;
import com.topone.Exception.FanZoneException;
import com.topone.Utils.ResultVOUntil;
import com.topone.VO.ResultVO;
import com.topone.dataObject.TcUser;
import com.topone.service.TcUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Created by Administrator on 2018/1/16,0016.
 */
@RestController
@RequestMapping("/buyer/userInfo")
@CrossOrigin
@Slf4j
public class BuyerInfoController{
    @Autowired
    private TcUserService service;

    @PostMapping("/updatePhone")
    public ResultVO<Map<String,Object>> updatePhone(@RequestParam("openid") String openid,
                                @RequestParam("handPhone") String handPhone,
                                Map<String,Object> map){

        if(StringUtils.isEmpty(handPhone)){
            log.error("【修改用户手机号】参数不正确,handPhone={}",handPhone);
            return ResultVOUntil.error(1,"【手机号码】参数不正确");

        }
        //如果openid或者手机号码为空 则
        if(StringUtils.isEmpty(openid)){
            log.error("【openid】参数不正确,openid={}",openid);
            return ResultVOUntil.error(1,"openId为空");
        }
        TcUser tcUser=new TcUser();
        try {
            tcUser = service.findByopenid(openid);
            if(tcUser==null){
                log.error("用户不存在",openid);
                map.put("error","用户名不存在");
                return ResultVOUntil.error(1,"用户不存在");

            }
            tcUser.setHandPhone(handPhone);
            service.save(tcUser);
        }catch (FanZoneException e) {
            log.error("【设置用户手机号】失败,openid={},phone={}",openid
                    ,handPhone);
            map.put("error",e.getMessage());
            return  ResultVOUntil.error(1,"设置用户手机号失败");
        }
            log.info("【设置用户手机号】成功 openid={},phone={}",openid,handPhone);
            map.put("success","修改成功");
            return ResultVOUntil.success(map);
    }
    @GetMapping("/tcUser")
    public  ResultVO<Map<String,Object>> findUserByopenid(@RequestParam("openid") String openid,
                                    Map<String,Object> map){
            try{
                TcUser tcUser=service.findByopenid(openid);
                map.put("tcUser",tcUser);
            }catch (FanZoneException e){
                log.error("【根据openid查询用户信息】失败,{}",e.fillInStackTrace());
                throw new FanZoneException(ResultEnum.USER_ERROR);
            }

            log.info("【根据openid查询用户信息】成功,{}",map);
            return ResultVOUntil.success(map);

    }
}
